package com.traffic.fuwu.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
    private List<String> excludedUrls;
    private String redirectUrl;

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object arg2) throws Exception {

        try {

            String fullUri = request.getRequestURI();
            if (fullUri.split("/").length == 3 && fullUri.indexOf("index") != -1) {
                //例如   /rootPath/index.html
                return true;
            }
            //String lasturi = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/"));
            for (String url : excludedUrls) {
                if (fullUri.equalsIgnoreCase(url) || fullUri.indexOf(url) != -1) {
                    return true;
                }

            }

            // intercept
            HttpSession session = request.getSession();
            // 判断是否登录
            

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 判断是否异步请求
     *
     * @return boolean
     */
    public static boolean isAsyncRequest(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("x-requested-with"));
    }

    /**
     * 鉴权不通过直接输出错误码
     *
     * @param servletResponse
     * @return PrintWriter
     */
    public PrintWriter getResponseWriter(HttpServletResponse servletResponse) {
        PrintWriter out = null;
        try {
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.setStatus(401);
            out = servletResponse.getWriter();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out;
    }
}
